﻿using System.Collections.Generic;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;

namespace ValidationFramework.Web.MVC.Extensions
{
	public static class CustomValidationSummaryExtensions
	{
		// constructor
		public static string CustomValidationSummary(this HtmlHelper htmlHelper, string summaryMessage, string summaryMessageWrapperTag, IDictionary<string, object> htmlAttributes)
		{
			var control = new StringBuilder();

			// Build summary message
			var messageTag = new TagBuilder(summaryMessageWrapperTag);
			messageTag.MergeAttribute("class", "validation-summary-message");
			messageTag.SetInnerText(summaryMessage);

			// Build list container
			var ulTag = new TagBuilder("ul");
			ulTag.MergeAttribute("class", "validation-summary-errors");

			// Build list
			var errorList = new StringBuilder();
			foreach (var pair in htmlHelper.ViewContext.ViewData.ModelState)
			{
				foreach (var error in pair.Value.Errors)
				{
					var listItemTagBuilder = new TagBuilder("li");
					listItemTagBuilder.SetInnerText(error.ErrorMessage);
					errorList.AppendLine(listItemTagBuilder.ToString(TagRenderMode.Normal));
				}
			}
			ulTag.InnerHtml = errorList.ToString();

			// Toggle Display. Rendering a hidden control provides hooks for client
			if (htmlHelper.ViewContext.ViewData.ModelState.IsValid)
			{
				messageTag.MergeAttribute("style", "display:none;");
				ulTag.MergeAttribute("style", "display:none;");
			}		

			// Fill control
			control.AppendLine(messageTag.ToString(TagRenderMode.Normal));
			control.AppendLine(ulTag.ToString(TagRenderMode.Normal));
			return control.ToString();
		}

		// overloads
		public static string CustomValidationSummary(this HtmlHelper htmlHelper)
		{
			return htmlHelper.CustomValidationSummary("There were some problems with your submission", "span", new { @class = "validation-summary-errors" });
		}
		public static string CustomValidationSummary(this HtmlHelper htmlHelper, string summaryMessage)
		{
			return htmlHelper.CustomValidationSummary(summaryMessage, "span", new
			                                                                      {
			                                                                          @class = "validation-summary-errors"
			                                                                      });
		}
		public static string CustomValidationSummary(this HtmlHelper htmlHelper, string summaryMessage, string summaryMessageWrapperTag)
		{
			return htmlHelper.CustomValidationSummary(summaryMessage, summaryMessageWrapperTag, new { @class = "validation-summary-errors" });
		}
		public static string CustomValidationSummary(this HtmlHelper htmlHelper, string summaryMessage, string summaryMessageWrapperTag, object htmlAttributes)
		{
			return htmlHelper.CustomValidationSummary(summaryMessage, summaryMessageWrapperTag, new RouteValueDictionary(htmlAttributes));
		}
	}
}
